/* ******************************************** */
/* * Tournament                               * */
/* * Authors: André Bannwart Perina           * */
/* *          Antonio Canabrava Fraideinberze * */
/* *          Willian Felipe Lopes da Silva   * */
/* ******************************************** */

#include <errno.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

/**
 * Executes the tournament between "amount" robots
 */
int main(int argc, char *argv[]) {
	if(5 != argc) {
		fprintf(stderr, "Usage: %s filesPrefix outputFile amount tournamentSize\n", argv[0]);
		return EXIT_FAILURE;
	}

	int i;
	int j;
	/* Number of files */
	int n = atoi(argv[3]);
	/* Tournament size */
	int t = atoi(argv[4]);
	/* Time fitness value */
	int tVal;
	/* Winner index */
	int minIdx;
	/* Random index */
	int rd;

	/* Distance fitness value, final fitness value */
	double dVal, fVal;
	/* Winner value */
	double min;

	/* Mount fileName */
	char *fileName = malloc((strlen(argv[1]) + ((int) log10(n)) + 2) * sizeof(char));

	/* Allocate set of used files (prevents tournament between the same file) */
	bool *usedSet = malloc(n * sizeof(bool));

	FILE *ipf;
	/* Open output file */
	FILE *opf = fopen(argv[2], "w");

	/* Error opening file */
	if(NULL == opf) {
		fprintf(stderr, "%s: %s: %s\n", argv[0], strerror(errno), argv[2]);
		return EXIT_FAILURE;
	}

	/* Random seed */
	srand(time(NULL));

	for(i = 0; i < n; i++) {
		/* Reset minimum */
		min = DBL_MAX;

		/* Reset set of used files */
		for(j = 0; j < n; j++)
			usedSet[j] = false;

		/* Run tournament */
		for(j = 0; j < t; j++) {
			/* Pick a file that wasn't picked before on this tournament */
			do
				rd = rand() % n;
			while(usedSet[rd]);

			/* Make this file picked */
			usedSet[rd] = true;

			/* Open file */
			sprintf(fileName, "%s%d", argv[1], rd);
			ipf = fopen(fileName, "r");

			/* Error opening file */
			if(NULL == ipf) {
				fprintf(stderr, "%s: %s: %s\n", argv[0], strerror(errno), fileName);
				return EXIT_FAILURE;
			}

			/* Read fitness values and close file */
			fscanf(ipf, "%d %lf", &tVal, &dVal);
			fclose(ipf);

			/* Calculate final value */
			fVal = tVal * dVal;

			/* If this is the smallest value, make this file the current winner */
			if(fVal < min) {
				min = fVal;
				minIdx = rd;
			}

			/* Print info. */
			printf("(Tournament %d candidate %d) File %d with value %lf\n", i, j, rd, fVal);
		}

		/* Save winner to output file */
		fprintf(opf, "%d %lf\n", minIdx, min);
	}

	/* Free everything */
	free(fileName);
	free(usedSet);
	fclose(opf);

	return EXIT_SUCCESS;
}
